#include <iostream>
#include <coroutine>
#include <fstream>
#include <string>
#include <utility>

// 协程的 promise 类型
struct FileReadPromise {
    std::string result;
    std::ifstream file;

    FileReadPromise(const std::string& filename) : file(filename) {}

    // 获取协程返回对象
    struct promise_type {
        FileReadPromise coro;

        FileReadPromise get_return_object() {
            return coro;
        }

        std::suspend_always initial_suspend() { return {}; }
        std::suspend_always final_suspend() noexcept { return {}; }
        void unhandled_exception() {}
        void return_void() { co_return; }
    };

    struct FileReadAwaiter {
        FileReadPromise& promise;

        bool await_ready() { return false; }

        // 修正 handle 的类型
        void await_suspend(std::coroutine_handle<promise_type> handle) {
            std::string line;
            if (std::getline(promise.file, line)) {
                promise.coro.result = std::move(line);
                handle.resume();
            } else {
                handle.destroy();
            }
        }

        std::string await_resume() {
            return promise.result;
        }
    };

    FileReadAwaiter read_line() {
        return FileReadAwaiter{*this};
    }
};

// 协程函数
FileReadPromise readFile(const std::string& filename) {
    co_await FileReadPromise(filename).read_line();
    co_return;
}

// 协程的调用
int main() {
    auto coro = readFile("example.txt");
    while (coro.file.is_open()) {
        std::string line = coro.result;
        if (!line.empty()) {
            std::cout << line << std::endl;
            coro = readFile("example.txt");
        } else {
            break;
        }
    }
    return 0;
}